package org.csu.mypetstore.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.persistence.AccountMapper;
import org.csu.mypetstore.persistence.OrderMapper;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class OrderController {
    @Autowired
    OrderService orderService;

    @Autowired
    AccountService accountService;

    static String oldOrderId = "";
    @CrossOrigin
    @PostMapping(value = "api/table")
    @ResponseBody
    public String common_Product(@RequestBody String quest) {
        //String[] array=  quest.split("\\.");
        //请求访问订单
        System.out.println(quest);
        JSONObject jsonObject = JSON.parseObject(quest);
        if(jsonObject.getString("params").equals("ordertable"))
        {
            List<Order> orderList =  orderService.getOrderList();
            String ret = "";
            for (int i=0; i<orderList.size(); i++){
                Order order = orderList.get(i);
                ret += order.getOrderId() + ",";
                ret += order.getUserId() + ",";
                ret += order.getTotalPrice() + ",";
                Account account =  accountService.getAccountByUserid(order.getUserId());
                //System.out.println("1111" + account.getPhoneInUse());
                ret += account.getPhoneInUse() + ",";
                //System.out.println(order.getStatus());
                String N = "N";
                String Y = "Y";
                if (order.getStatus().equals(N)){
                    ret += "未发货,";
                }else if (order.getStatus().equals(Y)){
                    ret += "已发货,";
                }
                ret += order.getOrderDate() + ",";
                ret += order.getShipFirstName() + ",";
                ret += order.getShipLastName() + ",";
                ret += order.getShipCountry() + " " +order.getShipState() + " " + order.getShipCity() + ",";
                ret += order.getShipaddr1() + ",";
                if (i == orderList.size() -1) {
                    ret += orderList.size();
                }
            }
            System.out.println(ret);
            return ret;
            //按照这个格式" id,name,money,reciever,address,phonenumber,state,date,pagetotal"返回，pagetotal为订单的总数比如
            // return "1,张三,123,广东省,已发货,2020-4-16,2,李四,123,广东省,已发货,2020-3-4,2"
//            return "1,张三,123,老张,广西省巴啦啦,15211146746,未发货,2019-2019," +
//                    "2,张四,123,老张,黑龙江省哈尔滨市,16344489652,已发货,2019-2019," +
//                    "3,李四,123,老李,广东省广州市,146325975631,已发货,2019-2019," +
//                    "4,王五,123,老王,天津,78623222632,已发货,2019-2019,4" ;
        }
        //请求搜索
        //通过地址进行搜索
        if(jsonObject.getString("params").equals("orderSearch_address"))
        {
            String addr = jsonObject.getString("address");
            List<Order> orderList =  orderService.searchOrderByAddr(addr);
            String ret = "";
            for (int i=0; i<orderList.size(); i++){
                Order order = orderList.get(i);
                ret += order.getOrderId() + ",";
                ret += order.getUserId() + ",";
                ret += order.getTotalPrice() + ",";
                Account account =  accountService.getAccountByUserid(order.getUserId());
                //System.out.println("1111" + account.getPhoneInUse());
                ret += account.getPhoneInUse() + ",";
                //System.out.println(order.getStatus());
                String N = "N";
                String Y = "Y";
                if (order.getStatus().equals(N)){
                    ret += "未发货,";
                }else if (order.getStatus().equals(Y)){
                    ret += "已发货,";
                }
                ret += order.getOrderDate() + ",";
                ret += order.getShipFirstName() + ",";
                ret += order.getShipLastName() + ",";
                ret += order.getShipCountry() + " " +order.getShipState() + " " + order.getShipCity() + ",";
                ret += order.getShipaddr1() + ",";
                if (i == orderList.size() -1) {
                    ret += orderList.size();
                }
            }
            System.out.println(ret);
            return ret;
            //按照这个格式" id,name,money,reciever,address,phonenumber,state,date,pagetotal"返回，pagetotal为订单的总数比如return "1,张三,123,广东省,已发货,2020-4-16,2,李四,123,广东省,已发货,2020-3-4,2"
            //return "1,刘六,123,老刘,广西省巴啦啦,13266359741,已发货,2019-2019," +
            //        "2,巴啦啦,123,老巴啦啦,黑龙江省哈尔滨市,1236955364268,已发货,2019-2019,2" ;
        }

        //通过用户名进行搜索
        if(jsonObject.getString("params").equals("orderSearch_name"))
        {
            String userId = jsonObject.getString("name");
            //System.out.println(userId);
            List<Order> orderList =  orderService.searchOrderByUser(userId);
            String ret = "";
            for (int i=0; i<orderList.size(); i++){
                Order order = orderList.get(i);
                ret += order.getOrderId() + ",";
                ret += order.getUserId() + ",";
                ret += order.getTotalPrice() + ",";
                Account account =  accountService.getAccountByUserid(order.getUserId());
                //System.out.println("1111" + account.getPhoneInUse());
                ret += account.getPhoneInUse() + ",";
                //System.out.println(order.getStatus());
                String N = "N";
                String Y = "Y";
                if (order.getStatus().equals(N)){
                    ret += "未发货,";
                }else if (order.getStatus().equals(Y)){
                    ret += "已发货,";
                }
                ret += order.getOrderDate() + ",";
                ret += order.getShipFirstName() + ",";
                ret += order.getShipLastName() + ",";
                ret += order.getShipCountry() + " " +order.getShipState() + " " + order.getShipCity() + ",";
                ret += order.getShipaddr1() + ",";
                if (i == orderList.size() -1) {
                    ret += orderList.size();
                }
            }
            System.out.println(ret);
            return ret;
            //按照这个格式" id,name,money,reciever,address,phonenumber,state,date,pagetotal"返回，pagetotal为订单的总数比如return "1,张三,123,广东省,已发货,2020-4-16,2,李四,123,广东省,已发货,2020-3-4,2"
            //return "1,小魔仙,123,老魔仙,广西省巴啦啦,15211114646,已发货,2019-2019," +
            //       "2,魔仙堡,123,老魔仙堡,黑龙江省哈尔滨市,15211146746,已发货,2019-2019,2" ;
        }

        //通过用户名和地址进行搜索
        if(jsonObject.getString("params").equals("orderSearch"))
        {
            String addr = jsonObject.getString("address");
            String userId = jsonObject.getString("name");
            List<Order> orderList =  orderService.searchOrderByBoth(addr,userId);
            String ret = "";
            for (int i=0; i<orderList.size(); i++){
                Order order = orderList.get(i);
                ret += order.getOrderId() + ",";
                ret += order.getUserId() + ",";
                ret += order.getTotalPrice() + ",";
                Account account =  accountService.getAccountByUserid(order.getUserId());
                //System.out.println("1111" + account.getPhoneInUse());
                ret += account.getPhoneInUse() + ",";
                //System.out.println(order.getStatus());
                String N = "N";
                String Y = "Y";
                if (order.getStatus().equals(N)){
                    ret += "未发货,";
                }else if (order.getStatus().equals(Y)){
                    ret += "已发货,";
                }
                ret += order.getOrderDate() + ",";
                ret += order.getShipFirstName() + ",";
                ret += order.getShipLastName() + ",";
                ret += order.getShipCountry() + " " +order.getShipState() + " " + order.getShipCity() + ",";
                ret += order.getShipaddr1() + ",";
                if (i == orderList.size() -1) {
                    ret += orderList.size();
                }
            }
            System.out.println(ret);
            return ret;
            //按照这个格式" id,name,money,reciever,address,phonenumber,state,date,pagetotal"返回，pagetotal为订单的总数比如return "1,张三,123,广东省,已发货,2020-4-16,2,李四,123,广东省,已发货,2020-3-4,2"
            //return "1,游乐王子,123,老王子,广西省巴啦啦,152111146746,已发货,2019-2019," +
            //        "2,巴啦啦,123,老头子,黑龙江省哈尔滨市,152111146746,已发货,2019-2019,2" ;
        }
        if (jsonObject.getString("params").equals("editOrder_reciever")){
            oldOrderId = jsonObject.getString("orderid");
            return "";
        }
        //编辑发货信息
        if(jsonObject.getString("params").equals("editSendInfo"))
        {
            Order order = new Order();
            //order.setUserId(jsonObject.getString("userId"));
            System.out.println(oldOrderId);
            order.setOrderId(oldOrderId);
            String address_1 = jsonObject.getString("address_1");
            String array1[] = address_1.split("\"");
            String country,city,state;
            if (array1.length != 1){
                System.out.println(array1[1] + array1[3] + array1[5]);
                country = array1[1];
                state = array1[3];
                city = array1[5];
            }else {
                String array2[] = address_1.split("\\s");
                System.out.println(array2[0] + array2[1] + array2[2]);
                country = array2[0];
                state = array2[1];
                city = array2[2];
            }
            System.out.println(country+state+city);
            order.setShipaddr1(jsonObject.getString("address_detailed"));
            order.setShipCity(city);
            order.setShipCountry(country);
            order.setShipState(state);
            order.setShipFirstName(jsonObject.getString("name_f"));
            order.setShipLastName(jsonObject.getString("name_l"));
            orderService.updateOrder(order);
            String userId = orderService.getUserIdByOrderId(oldOrderId);
            Account account = new Account();
            account.setUsername(userId);
            account.setPhoneInUse(jsonObject.getString("phonenumber"));
            orderService.updateAccount(account);
            return "editSendInfoOk";
        }
        //去发货
        if(jsonObject.getString("params").equals("toSend"))
        {
            orderService.send(jsonObject.getString("id"));
            //前端会将收货人姓名传过来,需要在数据库中修改发货信息，将状态修改为已发货
            //System.out.println(array[2]);
            return "SendSuccess";
        }
        if(jsonObject.getString("params").equals("checkOrder"))
        {
            List<Product> productList = orderService.getProductListByOrderId(jsonObject.getString("orderid"));
            String [] itemId = new String [100];
            String [] quantity = new String [100];
            for (int i=0; i<productList.size(); i++){
                itemId[i] = productList.get(i).getItemId();
                quantity[i] = productList.get(i).getSaleNum();
                //System.out.println(itemId[i]);
                //System.out.println(quantity[i]);
            }
            String [] productId = new String [100];
            for (int i=0; i<productList.size(); i++){
                productId[i] = orderService.getProductIdByItemId(itemId[i]);
                //System.out.println(productId[i]);
            }
            String [] categoryId = new String [100];
            for (int i=0; i<productList.size(); i++){
                categoryId[i] = orderService.getCategoryIdByProductId(productId[i]);
                //System.out.println(categoryId[i]);
            }
            String ret = "";
            for (int i=0; i<productList.size(); i++){
                ret += categoryId[i] + ",";
                ret += productId[i] + ",";
                ret += itemId[i] + ",";
                ret += quantity[i];
                if (i != productList.size()-1){ret += ",";}
            }
            System.out.println(ret);
            return ret;
            //System.out.println(array[2]+array[3]);
            //需要传入catagory、product、number，用","分隔开
            //String str="dog,golddog,1,cat,blackcat,2";
            //return str;
        }
        //删除订单
        if(jsonObject.getString("params").equals("del"))
        {
            String orderId = jsonObject.getString("orderid");
            orderService.deleteOrders(orderId);
            orderService.deleteOrderstatus(orderId);
            orderService.deleteLineItem(orderId);
            //前端会将用户姓名、下单时间传过来,删除相应订单
            return "delsuccessfully";
        }
        //删除部分订单
        if(jsonObject.getString("params").equals("delSomeOrder"))
        {
            JSONArray jsonArray = (JSONArray)jsonObject.get("delOrder_ids");
            for(int i = 0; i < jsonArray.size(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                String orderid = (String) obj.get("id");
                System.out.println(orderid);
                orderService.deleteOrders(orderid);
                orderService.deleteOrderstatus(orderid);
                orderService.deleteLineItem(orderid);
                }
            //前端会将用户姓名、下单时间传过来,删除相应订单
            return "delSuccess";
        }
        else {
            System.out.println("error");
            return "";
        }
    }
}
